package com.hxzy.servlet.message;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.bean.Message;
import com.hxzy.bean.User;
import com.hxzy.service.MessageService;
import com.hxzy.service.impl.MessageServiceImpl;
import com.hxzy.vo.JsonResult;
import com.hxzy.vo.StatusCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author nick
 */
@WebServlet("/publishMessage")
public class PublishServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        //获取页面发布到消息
        String share = req.getParameter("share");

        JsonResult jsonResult = new JsonResult();
        if (!Objects.nonNull(share)) { //做一次非空验证
            jsonResult.setCode(StatusCode.UNKNOWN_ERROR.getCode());
            jsonResult.setMessage(StatusCode.UNKNOWN_ERROR.getMessage());
            write2client(jsonResult, resp);
            return;
        }

        //从session作用域中获取当前登录的用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        if (null == user) { //说明session中不存在user，没有登录
            jsonResult.setCode(StatusCode.NOT_LOGIN.getCode());
            jsonResult.setMessage(StatusCode.NOT_LOGIN.getMessage());
            write2client(jsonResult, resp);
            return;
        }


        //组建Message对象
        Message message = new Message();
        message.setContent(share); //设置发布的内容
        message.setMesDate(LocalDateTime.now()); //设置当前时间为发布时间
        message.setAuthor(user);

        //调用Message业务逻辑层发布消息
        MessageService service = new MessageServiceImpl();
        int save = service.save(message);

        if (save > 0) {
            jsonResult.setCode(StatusCode.SUCCESS.getCode());
            jsonResult.setMessage(StatusCode.SUCCESS.getMessage());
        } else {
            jsonResult.setCode(StatusCode.EXCEPTION.getCode());
            jsonResult.setMessage(StatusCode.EXCEPTION.getMessage());
        }
        write2client(jsonResult, resp);
    }

    private void write2client(JsonResult jsonResult,HttpServletResponse resp) throws IOException {
        //将result转换为json
        String json = JSONObject.toJSONString(jsonResult);
        resp.getWriter().write(json);
        resp.getWriter().close();

    }
}
